<script setup lang="ts">
import type { ClinicDefaultAppointmentTimeDO, ClinicTimeCountRespVO } from '@/api/clinic-schedule';
import dayjs from 'dayjs';
import { computed, ref } from 'vue';
import { ClinicScheduleApi } from '@/api/clinic-schedule';
import { useRequest } from '@/hooks/useRequest';
import { buildAssetSource } from '@/utils';

const props = withDefaults(defineProps<{
  doctorId?: number
  clinicTime: ClinicTimeCountRespVO
  appointmentDate?: string
}>(), {
  appointmentDate: dayjs().format('YYYY-MM-DD')
});

const emit = defineEmits<{
  close: []
  confirm: [ClinicDefaultAppointmentTimeDO, {
    startTime: dayjs.Dayjs
    endTime: dayjs.Dayjs
  }]
}>();

const show = ref(false);

function handleClose() {
  show.value = false;
  emit('close');
  selectedTime.value = undefined;
}

const {
  data: appointTimeList,
  runAsync: getAppointmentTimeList
}
= useRequest(
  () => ClinicScheduleApi.getAppointmentTimeList({
    doctorId: props.doctorId,
    appointmentDate: props.appointmentDate,
    clinicTimePhaseIds: [props.clinicTime.id as number]
  }),
  {
    manual: true
  }
);

const selectedTime = ref<ClinicDefaultAppointmentTimeDO>();

function handleSelect(item: ClinicDefaultAppointmentTimeDO) {
  if (!isAvailable.value(item)) {
    uni.showToast({
      title: '该时间段无法预约',
      icon: 'none'
    });
    return;
  }
  selectedTime.value = item;
}

function handleConfirm() {
  if (!selectedTime.value) {
    uni.showToast({
      title: '请选择具体时间段',
      icon: 'none'
    });
    return;
  }
  emit('confirm', selectedTime.value, withAppointmentTimeRange(selectedTime.value));
  handleClose();
}

function withAppointmentTimeRange(item: ClinicDefaultAppointmentTimeDO) {
  const { appointmentTime } = item;
  const index = appointTimeList.value.indexOf(item);
  const isLast = index === appointTimeList.value?.length - 1;
  const endTime = isLast
    ? `${props.clinicTime.endTime}:00`
    : `${appointTimeList.value[index + 1]?.appointmentTime}`;
  return {
    startTime: dayjs(`${props.appointmentDate} ${appointmentTime}`, 'YYYY-MM-DD HH:mm:ss'),
    endTime: dayjs(`${props.appointmentDate} ${endTime}`, 'YYYY-MM-DD HH:mm:ss')
  };
}

const isAvailable = computed(() => {
  return (item: ClinicDefaultAppointmentTimeDO) => {
    const { endTime } = withAppointmentTimeRange(item);
    return endTime.isAfter(dayjs(), 'minute');
  };
});

defineExpose({
  onOpen() {
    show.value = true;
    getAppointmentTimeList();
  },
  onClose() {
    handleClose();
  }
});
</script>

<template>
  <view v-show="show" class="popup-overlay">
    <view class="app-popup">
      <view class="app-popup__hd">
        <view class="app-popup__title">
          选择具体时间段
        </view>
        <view class="app-popup__desc">
          请选择具体时间段预约
        </view>
        <view class="app-popup__close" @click="handleClose">
          <image :src="buildAssetSource('login-close.png')" class="h-54 w-54" />
        </view>
      </view>
      <view class="app-popup__content">
        <view class="min-h-200">
          <wd-row :gutter="34">
            <wd-col
              v-for="item in appointTimeList"
              :key="item.id"
              :span="8"
            >
              <view
                class="appointment-item__time"
                :class="{ active: selectedTime?.id === item.id, disabled: !isAvailable(item) }"
                @click="handleSelect(item)"
              >
                {{ withAppointmentTimeRange(item).startTime.format('HH:mm') }}
                -
                {{ withAppointmentTimeRange(item).endTime.format('HH:mm') }}
              </view>
            </wd-col>
          </wd-row>
        </view>

        <view class="flex-center">
          <view class="action-btn w-435">
            <wd-button block @click="handleConfirm">
              确认时间段
            </wd-button>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<style lang="scss" scoped>
.popup-overlay {
  @apply flex-center;
  position: fixed;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
  z-index: 10;
}

.app-popup {
  width: 886px;
  background: #fff;
  padding-bottom: 50px;
  border-radius: 20px;

  .app-popup__hd {
    position: relative;
    padding-left: 46px;
    padding-top: 56px;

    .app-popup__title {
      font-size: 54px;
      font-weight: bold;

      color: #333333;
    }
    .app-popup__desc {
      font-size: 24.25px;
      color: var(--secondary-text-color);
      margin-top: 20px;
    }
    .app-popup__close {
      position: absolute;
      top: 45px;
      right: 64px;
    }
  }

  .app-popup__content {
    padding: 0 20px;
    margin-top: 30px;

    .appointment-item__time {
      background: #e9f0fe;
      border-radius: 10px;
      color: #4a4a4a;
      font-size: 26px;
      padding: 22px 0;
      text-align: center;
      margin-top: 20px;
      &.disabled {
        background: #d9d9d9;
        color: #fff;
      }
      &.active {
        background: var(--primary);
        color: #fff;
      }
    }
  }

  .action-btn {
    --wot-button-medium-height: 89px;
    --wot-button-medium-fs: 36px;
    margin-top: 56px;

    :deep(.wd-button) {
      font-weight: bold;
    }
  }
}
</style>
